package com.dormitory.management.system.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dormitory.management.system.DAO.UpLoadHousemasterExcelFileDao;
import com.dormitory.management.system.DAO.UpLoadStudentExcelFileDao;
import com.dormitory.management.system.entity.*;
import com.dormitory.management.system.enums.UserEnum;
import com.dormitory.management.system.listener.UpLoadHousemasterExcelFileListener;
import com.dormitory.management.system.listener.UpLoadStudentExcelFileListener;
import com.dormitory.management.system.req.HousemasterPageReq;
import com.dormitory.management.system.req.HousemasterSaveReq;
import com.dormitory.management.system.req.HousemasterUpdateReq;
import com.dormitory.management.system.req.HousemasterUpdateRoomReq;
import com.dormitory.management.system.resp.HousemasterResp;
import com.dormitory.management.system.resp.StuAndHouResp;
import com.dormitory.management.system.service.HousemasterService;
import com.dormitory.management.system.mapper.BuildingMapper;
import com.dormitory.management.system.mapper.HousemasterMapper;
import com.dormitory.management.system.mapper.RoomMapper;
import com.dormitory.management.system.mapper.UserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dormitory.management.system.service.UserRoleService;
import com.dormitory.management.system.utils.EmailUtil;
import com.dormitory.managemnet.util.core.Result;
import com.dormitory.managemnet.util.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 宿管表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-12-17
 */
@Service
public class HousemasterServiceImpl extends ServiceImpl<HousemasterMapper, Housemaster> implements HousemasterService {

    @Autowired
    private UpLoadHousemasterExcelFileDao upLoadHousemasterExcelFileDao;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BuildingMapper buildingMapper;
    @Autowired
    private HousemasterMapper housemasterMapper;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    @Transactional
    public boolean save(HousemasterSaveReq req) {
        User user = new User();
        user.setUsername(req.getIdentityCard());
        //密码初始为后6位
        user.setPassword(req.getIdentityCard().substring(req.getIdentityCard().length()-6));
        //用户表插入
        if(userMapper.insert(user)>0){
            Housemaster housemaster = BeanUtil.copyProperties(req, Housemaster.class);
            user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername, req.getIdentityCard()));
            housemaster.setId(user.getId());
            //宿管表插入
            if(this.baseMapper.insert(housemaster)>0){
                //用户角色关联表插入
                return userRoleService.save(housemaster.getId(), UserEnum.USER_HOUSEMASTER.getRoleId());
            }
            return false;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        Housemaster housemaster = this.baseMapper.selectById(id);
        //宿管表删除
        if(this.baseMapper.deleteById(id)>0){
            //用户表删除
            if(userMapper.deleteById(id)>0){
                //用户角色关联表删除
                if(userRoleService.delete(id)) {
                    //房间信息更新
                    if(housemaster.getRoomId()!=null) {
                        if (roomMapper.update(null, new UpdateWrapper<Room>()
                                .setSql("current_number=current_number-1")
                                .eq("id", housemaster.getRoomId())) > 0) {
                            //更新楼栋表宿管名
                            return HousemasterNameUpdate(housemaster.getBuildingId());
                        }
                    }
                    return true;
                }
                return false;
            }
            return false;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean update(HousemasterUpdateReq req) {
        //更新宿管表
        if(this.baseMapper.updateById(BeanUtil.copyProperties(req,Housemaster.class))>0){
            User user = new User();
            user.setId(req.getId());
            user.setUsername(req.getIdentityCard());
            user.setPassword(req.getIdentityCard().substring(req.getIdentityCard().length()-6));
            //更新用户表
            return userMapper.updateById(user)>0;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean saveRoom(HousemasterUpdateRoomReq req) {
        //安排宿管楼栋房间
        if(this.baseMapper.updateById(BeanUtil.copyProperties(req, Housemaster.class))>0){
            //房间信息更新
            if(roomMapper.update(null,new UpdateWrapper<Room>()
                    .setSql("current_number=current_number+1")
                    .eq("id",req.getRoomId()))>0) {
                //更新楼栋表宿管名
                if(HousemasterNameUpdate(req.getBuildingId())){
                    //发送邮件
                    sendMail(req);
                    return true;
                }
                return false;
            }
            return false;
        }
        return false;
    }

    @Override
    @Transactional
    public boolean updateRoom(HousemasterUpdateRoomReq req) {
        //更新宿管楼栋房间
        if(this.baseMapper.updateById(BeanUtil.copyProperties(req, Housemaster.class))>0){
            //更新楼栋表宿管名
            return HousemasterNameAllUpdate();
        }
        return false;
    }

    @Override
    public IPage<HousemasterResp> getPage(HousemasterPageReq req) {
        return this.baseMapper.getHousemasterPage(new Page<>(req.getPageCurrent(),req.getPageSize()), new QueryWrapper<HousemasterResp>()
                .eq("status_id",0)
                .like(req.getIdentityCard()!=null,"identity_card",req.getIdentityCard())
                .eq(req.getSex()!=null,"sex",req.getSex())
                .eq(req.getBuildingId()!=null,"h.building_id",req.getBuildingId())
                .eq(req.getLivingId()!=null,"b.living_id",req.getLivingId())
                .like(req.getName()!=null,"name",req.getName())
                .like(req.getEmail()!=null,"email",req.getEmail())
                .like(req.getPhone()!=null,"phone",req.getPhone()));
    }

    //更新单楼栋表宿管名
    @Override
    @Transactional
    public boolean HousemasterNameUpdate(Long id){
        Building building = new Building();
        building.setId(id);
        List<Housemaster> housemasters = housemasterMapper.selectList(new QueryWrapper<Housemaster>().lambda()
                .eq(Housemaster::getBuildingId, id));
        buildingMapper.update(null,new UpdateWrapper<Building>().lambda().set(Building::getHousemaster,null).eq(Building::getId,id));
        String name="";
        boolean flag=true;
        if(housemasters.size()!=0) {
            for (Housemaster h : housemasters) {
                if (flag) {
                    name = h.getName();
                    flag = false;
                }else {
                    name = name + "," + h.getName();
                }
            }
            building.setHousemaster(name);
            return buildingMapper.updateById(building) > 0;
        }
        return true;

    }

    //更新全部楼栋表宿管名
    @Override
    @Transactional
    public boolean HousemasterNameAllUpdate(){
        List<Building> buildings = buildingMapper.selectList(null);
        String name;
        boolean flag;
        if(buildings.size()!=0) {
            for (Building building : buildings) {
                List<Housemaster> housemasters = housemasterMapper.selectList(new QueryWrapper<Housemaster>().lambda()
                        .eq(Housemaster::getBuildingId, building.getId()));
                name = "";
                flag = true;
                buildingMapper.update(null,new UpdateWrapper<Building>().lambda().set(Building::getHousemaster,null).eq(Building::getId,building.getId()));
                if (housemasters.size()!=0) {
                    for (Housemaster h : housemasters) {
                        if (flag) {
                            name = h.getName();
                            flag = false;
                        }else {
                            name = name + "," + h.getName();
                        }
                    }
                    building.setHousemaster(name);
                    buildingMapper.updateById(building);
                }
            }
            return true;
        }
        return true;
    }


    @Override
    public Result importHousemasterByExcel(String username, MultipartFile file) throws IOException {
        if (!file.getResource().exists()){
            return Result.error("传入文件没有收到");
        }
        if (!"xlsx".equals(file.getOriginalFilename().split("\\.")[1])){
            return Result.error("请传入.xlsx格式文件");
        }
        /**
         * 通过阿里巴巴的EasyExcel进行excel文件和题库id的上传存储进数据库
         * UpLoadExcelFileListener监听器
         */
        EasyExcel.read(file.getInputStream(), HousemasterExcel.class, new UpLoadHousemasterExcelFileListener(upLoadHousemasterExcelFileDao,username)).sheet().doRead();
        return Result.success("excel导入成功");
    }

    //管理员分配宿管寝室后发送
    private void sendMail(HousemasterUpdateRoomReq req){
        StuAndHouResp housemasterInfo = this.baseMapper.getHousemasterInfo(new QueryWrapper<StuAndHouResp>().eq("h.id", req.getId()));
        Email email = new Email("13958876486","工作人员","行政部");
        String emailHou = housemasterInfo.getEmail();
        String name = housemasterInfo.getName();
        String identityCard = housemasterInfo.getIdentityCard();
        String room=housemasterInfo.getLiving()+"-"+housemasterInfo.getBuilding()+"-"+housemasterInfo.getRoom();
        String sClass=req.getSClass();
        String sex = req.getSex();
        String content = email.assignToHou(name, identityCard, room, sClass, sex);
        String subject="账号信息请查收";
        String filePath=null;
        redisTemplate.opsForValue().set(emailHou+"***"+subject+"***"+content+"***"+filePath,"dxc",10, TimeUnit.SECONDS);
    }
}
